package com.wnhz.work.jy;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.wnhz.work.jy.activity.LoginActivity;
import com.wnhz.work.jy.activity.PurchaseCode;
import com.wnhz.work.jy.fragment.HomeFragment1;
import com.wnhz.work.jy.fragment.HomeFragment2;
import com.wnhz.work.jy.fragment.HomeFragment3;
import com.wnhz.work.jy.fragment.HomeFragment4;
import com.wnhz.work.jy.fragment.HomeFragment5;
import com.wnhz.work.jy.utils.MyUtils;

import java.util.ArrayList;
import java.util.List;

public class MyMain extends BaseActivity implements View.OnClickListener {
    private HomeFragment1 fragment1;
    private HomeFragment2 fragment2;
    private HomeFragment3 fragment3;
    private HomeFragment4 fragment4;
    private HomeFragment5 fragment5;

    private List<Fragment> fragmentList;
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;

    private RelativeLayout layout1, layout2, layout3, layout4, layout5;
    private ImageView image1, image2, image3, image4, image5;
    private TextView text1, text2, text3, text4, text5;

    private int textColorNor, textColorCli;
    private int position;

    private int[] bottomImgNor = {R.mipmap.ic_home_nor3, R.mipmap.ic_licai_nor3200x,
            R.mipmap.ic_chanpinzhongxin_nor, R.mipmap.ic_gouwuche_nor, R.mipmap.ic_wode_nor};
    private int[] bottomImgCli = {R.mipmap.ic_home1_li, R.mipmap.ic_licai_li,
            R.mipmap.ic_chanpinzhongxin_li, R.mipmap.ic_gouwuche1_li, R.mipmap.ic_wode1_li1};

    /**
     * 扫描跳转Activity RequestCode
     */
    public static final int REQUEST_CODE = 111;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 845;
    public int f3 = 10;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_main);

        initData();
        initView();
    }

    private void initData() {
        textColorNor = getResources().getColor(R.color.main_text_normal);
        textColorCli = getResources().getColor(R.color.main_color);
    }

    public List<View> tab_lay = new ArrayList<>();
    private void initView() {

        layout1 = (RelativeLayout) findViewById(R.id.tab1);
        layout2 = (RelativeLayout) findViewById(R.id.tab2);
        layout3 = (RelativeLayout) findViewById(R.id.tab3);
        layout4 = (RelativeLayout) findViewById(R.id.tab4);
        layout5 = (RelativeLayout) findViewById(R.id.tab5);
        tab_lay.add(layout1);
        tab_lay.add(layout2);
        tab_lay.add(layout3);
        tab_lay.add(layout4);
        tab_lay.add(layout5);
        image1 = (ImageView) findViewById(R.id.main_image1);
        image2 = (ImageView) findViewById(R.id.main_image2);
        image3 = (ImageView) findViewById(R.id.main_image3);
        image4 = (ImageView) findViewById(R.id.main_image4);
        image5 = (ImageView) findViewById(R.id.main_image5);

        text1 = (TextView) findViewById(R.id.main_text1);
        text2 = (TextView) findViewById(R.id.main_text2);
        text3 = (TextView) findViewById(R.id.main_text3);
        text4 = (TextView) findViewById(R.id.main_text4);
        text5 = (TextView) findViewById(R.id.main_text5);

        layout1.setOnClickListener(this);
        layout2.setOnClickListener(this);
        layout3.setOnClickListener(this);
        layout4.setOnClickListener(this);
        layout5.setOnClickListener(this);

        fragmentList = new ArrayList<>();
        fragment1 = new HomeFragment1();
        fragment2 = new HomeFragment2();
        fragment3 = new HomeFragment3();
        fragment4 = new HomeFragment4();
        fragment5 = new HomeFragment5();

        fragmentList.add(fragment1);
        fragmentList.add(fragment2);
        fragmentList.add(fragment3);
        fragmentList.add(fragment4);
        fragmentList.add(fragment5);

        fragmentManager = getSupportFragmentManager();
        transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.main_content, fragment1);
        transaction.add(R.id.main_content, fragment2);
        transaction.add(R.id.main_content, fragment3);
        transaction.add(R.id.main_content, fragment4);
        transaction.add(R.id.main_content, fragment5);

        transaction.hide(fragment2);
        transaction.hide(fragment3);
        transaction.hide(fragment4);
        transaction.hide(fragment5);

        transaction.commit();

        image1.setImageResource(bottomImgCli[0]);
        text1.setTextColor(textColorCli);
    }

    private void hideFragment() {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragmentList.size(); i++) {
            transaction.hide(fragmentList.get(i));
        }
        transaction.commit();
    }

    private void initBottomView() {
        image1.setImageResource(bottomImgNor[0]);
        image2.setImageResource(bottomImgNor[1]);
        image3.setImageResource(bottomImgNor[2]);
        image4.setImageResource(bottomImgNor[3]);
        image5.setImageResource(bottomImgNor[4]);

        text1.setTextColor(textColorNor);
        text2.setTextColor(textColorNor);
        text3.setTextColor(textColorNor);
        text4.setTextColor(textColorNor);
        text5.setTextColor(textColorNor);
    }


    @Override
    public void onClick(View v) {
        Intent intent;

        if (fragment4.isediting()){
            return;
        }
        initBottomView();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        switch (v.getId()) {
            case R.id.tab1:
                hideFragment();
                transaction.show(fragmentList.get(0)).commit();
                image1.setImageResource(bottomImgCli[0]);
                text1.setTextColor(textColorCli);
                fragment1.onResume();
                break;

            case R.id.tab2:
                hideFragment();
                transaction.show(fragmentList.get(1)).commit();
                image2.setImageResource(bottomImgCli[1]);
                text2.setTextColor(textColorCli);
                break;

            case R.id.tab3:
                hideFragment();
                transaction.show(fragmentList.get(2)).commit();
                image3.setImageResource(bottomImgCli[2]);
                text3.setTextColor(textColorCli);
                break;

            case R.id.tab4:
                if (MyApplication.getInstance().userBean != null) {
                    hideFragment();
                    transaction.show(fragmentList.get(3)).commit();
                    image4.setImageResource(bottomImgCli[3]);
                    text4.setTextColor(textColorCli);
                    fragment4.home4getData();
                } else {
                    intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("from", "fragment4");
                    startActivity(intent);
                }
                break;

            case R.id.tab5:
                if (MyApplication.getInstance().userBean != null) {
                    hideFragment();
                    transaction.show(fragmentList.get(4)).commit();
                    image5.setImageResource(bottomImgCli[4]);
                    text5.setTextColor(textColorCli);
                    fragment5.onResume();

                } else {
                    intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("from", "fragment5");
                    startActivity(intent);
                }

                break;

            default:
                break;
        }
    }

    private long exitTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次后退键退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                // 退出代码
//                MyApplication.isLogin = false;
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        position = intent.getIntExtra("Pagination", 0);

        fragment5.setHeadImage();
        switch (position) {
            case 0:
                onClick(layout1);
                break;

            case 1:
                onClick(layout2);
                break;

            case 2:
                onClick(layout3);
//                fragment3.jump();
                break;

            case 3:
                onClick(layout4);
                break;

            case 4:
                onClick(layout5);
                break;

            default:
                break;
        }
    }

    public void setFragment(int tab) {
        switch (tab) {
            case 3:
                onClick(layout3);
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onStop() {
        super.onStop();
        MyUtils.isBackground(getApplication());
    }

    @Override
    protected void onStart() {
        super.onStart();
        //MyUtils.isBackground(getApplication());
    }

    public void scanCode(){
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE);
        } else {
            startActivityForResult(new Intent(this, CaptureActivity.class), REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startActivityForResult(new Intent(this, CaptureActivity.class), REQUEST_CODE);
            }else {
                MyToast("很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。");
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private static final String TAG = "MyMain";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    String p = "pid/";
                    String g = "guiyuanOrderid/";

                    if (result.indexOf("guiyuanOrderid/")<=0 || result.indexOf(p)<=0||result.indexOf(g)<=0){
                        MyToast("二维码错误");
                    }else {
                        String pid = result.substring(result.indexOf(p)+p.length(),result.indexOf("guiyuanOrderid/")-1);
                        String guiyuanOrderid = result.substring(result.indexOf(g)+g.length(),result.length());
                        Log.e(TAG, "onActivityResult: "+pid);
                        Log.e(TAG, "onActivityResult: "+guiyuanOrderid);
                        Intent intent = new Intent(this, PurchaseCode.class);
                        intent.putExtra("pid",pid);
                        intent.putExtra("orderId",guiyuanOrderid);
                        startActivity(intent);
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
